package com.jingyuan.biz.event.listener;

import com.jingyuan.biz.event.OffLineEvent;
import com.jingyuan.biz.manager.JNode;
import com.jingyuan.biz.manager.JNodeManager;
import com.jingyuan.biz.manager.VoteProcessManager;
import com.jingyuan.common.entity.EventType;
import com.jingyuan.common.entity.HostInfo;
import com.jingyuan.common.entity.utils.SpringUtil;
import com.jingyuan.common.entity.ServerMessage;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class OffLineListener extends EventListener<OffLineEvent> {
    @Resource
    private VoteProcessManager voteProcessManager;

    @Override
    public void actionListener(OffLineEvent event) {
        JNodeManager manager=SpringUtil.getBean(JNodeManager.class);
        JNode offLineNode=event.getNode();
        List<JNode> jNodeList=manager.getHostNode();
        //移除主机节点
        manager.removeNode(null,offLineNode);

        for(JNode node:jNodeList){
            ServerMessage response=new ServerMessage();
            HostInfo hostInfo=new HostInfo();
            hostInfo.setAddress(offLineNode.getAddress());
            hostInfo.setPort(offLineNode.getPort());
            response.setHost(hostInfo);
            String isActive=event.isActive() ? "主动" : "被动";
            response.setMsg(String.format("----------------------机器IP：%s %s下线-------------------",offLineNode.getAddress(),isActive));
            Channel channel=node.getChannel();
            channel.writeAndFlush(response);
        }
        //下线的这台主机节点是Master节点
        if(offLineNode.getIsMaster()){
            voteProcessManager.startVoting();
        }
    }

    public OffLineListener(){
        setListenEventType(EventType.OFFLINE);
    }
}
